package com.share.rabbitmq.quickstart;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
import com.share.rabbitmq.RabbitMQConnection;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * author:caifan
 * date:2020/3/1
 */
public class QuickProducer {
    private static final String QUEUE_NAME = "queue_01";

    public static void main(String[] args) throws Exception {
        Connection connect = RabbitMQConnection.connect();
        //simpleSendMessage(connect);
        messageAck(connect);
        connect.close();
    }

    /**
     * 消息确认
     * @param connect
     * @throws Exception
     */
    public static void messageAck(Connection connect) throws Exception {
        final String exchangeName = "my.exchange.direct";
        final String queueName = "my.exchange.queue";
        final String routingKey = "my.test.ack";

        String dlxExchangeName = "my.dlx.topicExchange";
        String dlxRouting_key1 = "my.dlx.topic.abc";

        Channel channel = connect.createChannel();
        //持久化队列
        Map<String, Object> argMap = new HashMap<>();
        argMap.put("x-dead-letter-exchange", dlxExchangeName);
        argMap.put("x-dead-letter-routing-key", dlxRouting_key1);

        channel.queueDeclare(queueName, true, false, false, argMap);
//        channel.exchangeDeclare(exchangeName, "direct", true);
//        channel.queueBind(queueName, exchangeName,  "my.test.ack");
        String body = "{\"name\":\"含山\", \"address\":\"广州\"}";
        AMQP.BasicProperties basicProperties = MessageProperties.PERSISTENT_TEXT_PLAIN;
        basicProperties.builder().contentType("application/json")//设置json格式
                .deliveryMode(2)    //持久化
                .correlationId(UUID.randomUUID().toString());
        channel.basicPublish(exchangeName, routingKey, true, basicProperties, body.getBytes());
    }

    /**
     * 简单的发送消息
     * @param connect
     * @throws Exception
     */
    public static void simpleSendMessage(Connection connect) throws Exception {
        Channel channel = connect.createChannel();
        /*
         * 如果队列不存在则创建队列
         */
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        for (int i = 0;i < 10;i++) {
            String message = "hello rabbitmq" + i;
            /*
             * 消息发送的时候如果没有指定具体的交换机，那么就会发送到rabbimtq指定默认的交换机上，
             * 那么该交换机就会去根据routing_key 查找对应的queueName 然后发送的该队列上
             */
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        }
        channel.close();
    }

}
